package com.xinjie.www.servlet;

import com.xinjie.www.po.Manager;
import com.xinjie.www.po.User;
import com.xinjie.www.service.manager.ManagerServiceImpl;
import com.xinjie.www.service.user.UserService;
import com.xinjie.www.service.user.UserServiceImpl;
import com.xinjie.www.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String identity = req.getParameter("identity");
        if (identity == null) {
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
        if ("用户".equals(identity)) {
            //用户登录
            String name = req.getParameter("name");
            String password = req.getParameter("password");
            System.out.println(name);
            System.out.println(password);
            UserService userService = new UserServiceImpl();
            User user = userService.login(name, password);
            if (user != null) {
                req.getSession().setAttribute(Constants.USER_SESSION, user);
                req.getSession().setAttribute("success","登陆成功");
                resp.sendRedirect("/UserPage/UserFrame.jsp");
                User user1 =(User) req.getSession().getAttribute(Constants.USER_SESSION);
            } else {
                System.out.println("用户名密码错误");
                req.setAttribute("error", "用户名或者密码不正确");
                resp.sendRedirect("/login.jsp");
            }
        } else {
            //管理员登录
            String name = req.getParameter("name");
            String password = req.getParameter("password");
            ManagerServiceImpl managerService = new ManagerServiceImpl();
            Manager manager = managerService.login(name, password);
            if (manager != null) {
                req.getSession().setAttribute(Constants.MANAGER_SESSION, manager);
                req.getSession().setAttribute("success","登陆成功");
                resp.sendRedirect("/ManagerPage/ManagerFrame.jsp");
            } else {
                req.setAttribute("error", "用户名或者密码不正确");
                resp.sendRedirect("/login.jsp");
            }

        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}